package com.songshuai.webapi.logs.service.request;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.songshuai.webapi.logs.entity.PermissionLog;
import com.songshuai.webapi.logs.mqchannel.InputSource;
import com.songshuai.webapi.logs.repository.PermissionLogsRepository;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.integration.annotation.ServiceActivator;

import java.util.concurrent.CompletableFuture;
/**
 * Created by yubo on 2018/12/11.
 */
@EnableBinding(InputSource.class)
public class PermissionLogsService {

    private static Logger logger = LoggerFactory.getLogger(PermissionLogsService.class);

    @Autowired
    private PermissionLogsRepository permissionLogsRepository;

    @ServiceActivator(inputChannel = InputSource.PERMISSIONSCHANNEL, outputChannel = InputSource.REPLYCHANNEL)
    public CompletableFuture<String> accept(String log) {
        return CompletableFuture.supplyAsync(() -> {
            if(StringUtils.isNotBlank(log)){
                PermissionLog permissionLog = null;
                try {
                    permissionLog = new Gson().fromJson(log, PermissionLog.class);
                } catch (JsonSyntaxException e) {
                    logger.error("保存日志抛出异常",e);
                }
                permissionLogsRepository.save(permissionLog);
            }
            return "1";
        });
    }
}